package movieGandalf.dbParser;

import java.io.BufferedReader;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import movieGandalf.database.MovieTools;

public class DirectorsAdder implements DataReader{
	
	public int read(Connection conn, BufferedReader in){
		String line = null;
		PreparedStatement stmt = null;
		
		String imdbName = null;
		BigInteger movieID = null;
		String directorName = null;
		BigInteger directorID = null;
		
		try {		
			
			stmt = conn.prepareStatement("CREATE TEMPORARY TABLE IF NOT EXISTS DbMysql06.TempDirectors (movieID BIGINT UNSIGNED, directorID BIGINT UNSIGNED, PRIMARY KEY (movieID));");
			stmt.execute();
			stmt.close();
			
			stmt = conn.prepareStatement("REPLACE INTO TempDirectors (movieID,directorID) VALUES(?,?)");
			
			boolean isBegin = true;
			
			while ((line = in.readLine()) != null){
				int len=line.length();
				
				if (isBegin){
					if (len<6 || !line.subSequence(0, 4).equals("Name") || !line.subSequence(len-6, len).equals("Titles"))
						continue;
					else{
						isBegin = false;
						line = in.readLine();
						continue;
					}
				}
				
				if (len>=5 && line.startsWith("-----"))
					break;
				
				if (len==0 || line.charAt(0)=='"')
					continue;
				
				int i = 0;
				
				for (i=0;i<len;i++){
					if (line.charAt(i)=='\t') {
						break;
					}
				}
				
				if (i>0){
					directorName = line.substring(0,i);
					if (!MovieTools.directorValidator(directorName))
						continue;
					
					directorID = MovieTools.getDirectorID(conn, directorName);
					if (directorID == null)
						continue;
				}
				
				line = line.substring(i, len).trim()+"\t";
				imdbName = ParserTools.getIMDBName(line);
				if (!MovieTools.movieValidator(imdbName))
					continue;

				movieID = MovieTools.getMovieID(conn, imdbName);
				if (movieID == null)
					continue;
				
				stmt.setObject(1, movieID);
				stmt.setObject(2, directorID);
				stmt.addBatch();
			}
			
			try{
				stmt.executeBatch();
			}
			catch(Exception e){}
			finally{
				conn.commit();
				stmt.close();
			}
			
			stmt = conn.prepareStatement("UPDATE Movies INNER JOIN TempDirectors ON Movies.movieID=TempDirectors.movieID SET Movies.directorID = TempDirectors.directorID");
			stmt.addBatch();
			try{
				stmt.executeBatch();
			}
			catch(Exception e){}
			finally{
				conn.commit();
				stmt.close();
			}
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
